/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.android.apps.mytracks.services.sensors.ant;

import com.dsi.ant.AntDefine;
import com.dsi.ant.exception.AntInterfaceException;

import android.content.Context;

/**
 * This class provides common functionality used by subclasses of
 * {@link AntSensorManager}.
 *
 * @author Matthew Simmons
 */
// TODO: Fold this into AntSensorManager once AntSRMSensorManager becomes a
// subclass of this one.
abstract class AbstractAntSensorManager extends AntSensorManager {
  private static final byte NETWORK_NUMBER = 1;  // ANT+
  private static final byte TRANSMIT_TYPE = WILDCARD;
  private static final short CHANNEL_PERIOD = 8070;
  private static final byte RF_FREQUENCY = 57;
  private static final byte PROXIMITY_SEARCH_THRESHOLD = 0;

  public AbstractAntSensorManager(Context context) {
    super(context);
  }

  @Override
  protected final boolean handleMessage(byte messageId, byte[] messageData)
      throws AntInterfaceException {
    if (super.handleMessage(messageId, messageData)) {
      return true;
    }

    byte channel = (byte) (messageData[0] & AntDefine.CHANNEL_NUMBER_MASK);
    handleOneMessage(channel, messageId, messageData);
    return true;
  }

  /**
   * Handle an ANT message.
   * @param channel the channel for which the message is intended
   * @param messageID the ID of the ANT message
   * @param messageData the raw ANT message data, including the channel
   */
  protected abstract void handleOneMessage(byte channel, byte messageId, byte[] messageData)
      throws AntInterfaceException;

  /**
   * Set up a channel for a particular sensor.  Prefer this method to
   * {@link #setupAntSensorChannel(byte, byte, short, byte, byte, short, byte, byte)}.
   */
  protected void setupAntSensorChannel(byte channelNumber, short deviceNumber, byte deviceType) {
    setupAntSensorChannel(NETWORK_NUMBER, channelNumber, deviceNumber, deviceType, TRANSMIT_TYPE,
        CHANNEL_PERIOD, RF_FREQUENCY,
        PROXIMITY_SEARCH_THRESHOLD);
  }
}
